#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 例子,单线程,多线程比较的例子的多进程版本
import multiprocessing,datetime
"""
# 计算
def calc(i):
    sum = 0
    for _ in range(1000000000):
        sum += 1
    print(i,sum)

if __name__=="__main__":
    start = datetime.datetime.now()

    ps = []
    for i in range(5):
        p = multiprocessing.Process(target=calc,args=(i,),name="calc-{}".format(i))
        ps.append(p)
        p.start()
    for p in ps:
        p.join()

    delta = (datetime.datetime.now() - start).total_seconds()
    print(delta)
    print('end===')
# 单线程,多线程运行了4分钟,多进程用了一分半,这是真并行.
# 注意: __name__=="__main__"多进程代码一定要放在这下面执行.
"""



# 进程池举例
import logging,datetime,multiprocessing

# 日志打印进程id,进程名,线程id,线程名
logging.basicConfig(level=logging.INFO,format="%(process)d %(processName)s %(thread)d %(message)s")

# 计算
def calc(i):
    sum = 0
    for _ in range(1000): # 增大这个值观察效果,
        sum += 1
    logging.info('{}.in function'.format(sum))
    return sum # 进程要return,callback才可以拿到这个效果.

if __name__=='__main__':
    start = datetime.datetime.now()
    pool = multiprocessing.Pool(5)
    for i in range(5):
        # 回调函数必须接受一个参数
        pool.apply_async(calc,args=(i,),callback=lambda x: logging.info('{}. in callback'.format(x))) #异步执行.
    pool.close()
    pool.join()

    delta = (datetime.datetime.now() - start).total_seconds()
    print(delta)
    print('end===')
    